import sys
import platform
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget,
                             QDateEdit, QSpinBox, QPushButton, QLabel, 
                             QFileDialog, QComboBox, QMenu)
from PyQt5.QtCore import QDate, Qt
from PyQt5.QtGui import QClipboard
import configparser
import traceback
from pathlib import Path

def format_system_path(path):
    """根据系统类型格式化路径"""
    path_obj = Path(path).resolve()
    if platform.system() == 'Windows':
        return str(path_obj).replace('/', '\\')
    return str(path_obj)
sys.path.append(str(Path(__file__).parent.parent))
from ktt_core_new import orders

class KTTGUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.init_ui()
        self.load_config()
        
    def init_ui(self):
        # 主窗口设置
        self.setWindowTitle('KTT业务处理系统')
        self.setGeometry(300, 300, 400, 300)
        
        # 主布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout()
        
        # 序号选择器 (1-10)
        self.seq_spin = QSpinBox()
        self.seq_spin.setRange(1, 10)
        self.seq_spin.setValue(1)
        layout.addWidget(QLabel('选择序号:'))
        layout.addWidget(self.seq_spin)
        
        # 文件选择按钮
        self.file_btn = QPushButton('选择文件')
        self.file_btn.clicked.connect(self.select_files)
        layout.addWidget(self.file_btn)
        
        # 执行按钮
        self.execute_btn = QPushButton('生成订单')
        self.execute_btn.clicked.connect(self.execute_processing)
        layout.addWidget(self.execute_btn)
        
        # 状态显示(可复制)
        self.status_label = QLabel('准备就绪')
        self.status_label.setTextInteractionFlags(Qt.TextSelectableByMouse | Qt.TextSelectableByKeyboard)
        self.status_label.setCursor(Qt.IBeamCursor)
        self.status_label.setContextMenuPolicy(Qt.CustomContextMenu)
        self.status_label.customContextMenuRequested.connect(self.show_context_menu)
        layout.addWidget(self.status_label)
        
        central_widget.setLayout(layout)
    
    def load_config(self):
        config_path = Path(__file__).parent / 'config.ini'
        if not config_path.exists():
            raise FileNotFoundError(f"配置文件不存在: {config_path}")

        self.config = configparser.ConfigParser()
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                self.config.read_file(f)
        except Exception as e:
            raise ValueError(f"配置文件读取失败: {str(e)}")
        
        # 验证必要配置项
        required_keys = ['input_xlsx_dir', 'output_dir']
        for key in required_keys:
            if key not in self.config['PATHS']:
                raise ValueError(f"配置文件中缺少必要项: PATHS/{key}")
        
    def copy_status_text(self):
        """复制状态文本到剪贴板"""
        clipboard = QApplication.clipboard()
        clipboard.setText(self.status_label.text())

    def show_context_menu(self, pos):
        """显示右键上下文菜单"""
        menu = QMenu()
        copy_action = menu.addAction("复制")
        copy_action.triggered.connect(self.copy_status_text)
        menu.exec_(self.status_label.mapToGlobal(pos))

    def select_files(self):
        options = QFileDialog.Options()
        file, _ = QFileDialog.getOpenFileName(
            self, "选择Excel文件",
            self.config['PATHS']['input_xlsx_dir'],
            "Excel Files (*.xlsx)",
            options=options)
        
        if file:
            self.selected_file = file
            self.status_label.setText(f"已选择: {Path(file).name}")
    
    def execute_processing(self):
        import pywintypes
        if not hasattr(self, 'selected_file'):
            self.status_label.setText("请先选择Excel文件")
            return
            
        seq_str = f"{self.seq_spin.value():02d}"
        
        # 更新处理状态
        current_file = Path(self.selected_file).name
        self.status_label.setText(f"{current_file}   正在处理...")
        QApplication.processEvents()  # 强制立即更新UI
        
        try:
            # 初始化orders实例
            order_processor = orders(config_dir=self.config['PATHS']['source_dir'],save_temp_root_dir=self.config['PATHS']['root_output_dir'])
            
            # 格式化路径并打印调试信息
            formatted_path = format_system_path(self.selected_file)
            print(f"系统类型: {platform.system()}")
            print(f"格式化后路径: {formatted_path}")
            
            # 调用generate_order_to_supplier
            output_path = order_processor.generate_order_to_supplier(
                order_fn_input=formatted_path,
                seq_no=seq_str,
                sheet_name='商品列表',
                expand_qty='yes'
            )

            
            if isinstance(output_path, list):
                file_names = [str(Path(p).name) for p in output_path]  # 确保转为字符串
                status_text = "成功处理:\n" + "\n".join(file_names)
                self.status_label.setText(status_text)
            else:
                self.status_label.setText(f"成功处理: {Path(output_path).name}")
            
            # 打开输出目录 (处理单文件和列表情况)
            output_dir = Path(output_path[0] if isinstance(output_path, list) else output_path).parent
            if platform.system() == 'Windows':
                import os
                os.startfile(output_dir)
            elif platform.system() == 'Darwin':  # MacOS
                import subprocess
                subprocess.run(['open', str(output_dir)])
            else:  # Linux
                import subprocess
                subprocess.run(['xdg-open', str(output_dir)])
        except pywintypes.com_error as e:
            error_detail = f"""
            Excel操作错误:
            - 文件路径: {self.selected_file}
            - 错误代码: {e.excepinfo[5] if len(e.excepinfo) > 5 else 'N/A'}
            - 错误描述: {e.excepinfo[2] if len(e.excepinfo) > 2 else str(e)}
            """
            print(error_detail)
            self.status_label.setText("Excel文件访问失败，请检查文件是否被占用")
        except Exception as e:
            error_msg = f"处理错误:\n{traceback.format_exc()}"
            print(error_msg)
            self.status_label.setText(f"错误: {str(e)}")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    gui = KTTGUI()
    gui.show()
    sys.exit(app.exec_())
